﻿using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        public static void CopyToImage()
        {
            if (Globals.selectedEditor == null) return;
            if (Globals.selectedEditor.SelectedExpression == null) return;

            LunarPresentation.Expressions.Expression curEx
                = Globals.selectedEditor.SelectedExpression;

            if (curEx.ExBackground == Brushes.Transparent &&
                curEx.Editor.DefaultBackground == Brushes.Transparent)
            {
                MessageBox.Show("当前文档和当前公式的背景色都是透明色，这样复制的图像会是个黑墨团！\r\n" +
                    "如果真的要使用透明背景的公式图片数据，请使用“公式导出为图像”命令导出一个带透明底色的ＰＮＧ图片文件。\r\n" +
                    "否则请修改文档背景色或公式背景色（例如白色）再复制图像数据。",
                    Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            RenderTargetBitmap rtb = new RenderTargetBitmap((int)curEx.ActualWidth, (int)curEx.ActualHeight,
                96, 96, PixelFormats.Pbgra32);

            if (curEx is Expressions.StackPanelExpression)
            {
                Expressions.StackPanelExpression pEx = curEx as Expressions.StackPanelExpression;

                Brush preBack = pEx.ExBackground;
                if (preBack == Brushes.Transparent)
                {
                    pEx.BasePanel.Background = pEx.Editor.DefaultBackground;
                }

                Brush tmp = curEx.MainBorder.BorderBrush;

                curEx.MainBorder.BorderBrush = pEx.Editor.DefaultBackground;

                pEx.InvalidateArrange();
                pEx.UpdateLayout();
                rtb.Render(curEx.Child as Visual);

                curEx.MainBorder.BorderBrush = tmp;

                if (preBack == Brushes.Transparent)
                {
                    pEx.BasePanel.Background = Brushes.Transparent;
                }
            }
            else
            {
                Brush preBack = curEx.MainBorder.Background;

                if (preBack == Brushes.Transparent)
                {
                    curEx.MainBorder.Background = curEx.Editor.DefaultBackground;
                }

                Brush tmp = curEx.MainBorder.BorderBrush;
                curEx.MainBorder.BorderBrush = curEx.Editor.DefaultBackground;

                curEx.MainBorder.InvalidateArrange();
                curEx.MainBorder.UpdateLayout();
                rtb.Render(curEx.Child as Visual);

                curEx.MainBorder.BorderBrush = tmp;

                if (preBack == Brushes.Transparent)
                {
                    curEx.MainBorder.Background = preBack;
                }
            }

            Clipboard.SetImage(rtb);
        }
    }
}
